package main

import (
	"context"
	"database/sql"
	"log"

	"saasems/database"
	"saasems/models"
)

// RegisterDevice 注册单个设备
func RegisterDevice(ctx context.Context, db *database.PostgresDB, device *models.Device) error {
	tx, err := db.BeginTxx(ctx, nil)
	if err != nil {
		log.Printf("事务开启失败: %v", err)
		return err
	}
	defer db.Rollback(tx)

	// 检查设备是否已存在
	var existingID int
	if err := tx.GetContext(ctx, &existingID,
		"SELECT id FROM devices WHERE tenant_id = $1 AND device_id = $2",
		device.TenantID, device.DeviceID); err == nil {
		log.Printf("设备已存在 (ID: %d)", existingID)
		return err
	}

	// 插入新设备
	err = tx.NamedExecContext(ctx, `
		INSERT INTO devices (
			tenant_id, 
			device_id, 
			is_gateway,
			parent_gateway_id,
			metadata
		) VALUES (
			:tenant_id,
			:device_id,
			:is_gateway,
			:parent_gateway_id,
			:metadata
		)`, device)
	if err != nil {
		log.Printf("设备插入失败: %v", err)
		return err
	}

	return db.Commit(tx)
}

// RegisterGatewayWithSubDevices 注册网关及其子设备
func RegisterGatewayWithSubDevices(ctx context.Context, db *database.PostgresDB, gateway *models.Device, subDevices []*models.Device) error {
	tx, err := db.BeginTxx(ctx, nil)
	if err != nil {
		log.Printf("事务开启失败: %v", err)
		return err
	}
	defer db.Rollback(tx)

	// 设置网关标志
	gateway.IsGateway = true

	// 先注册网关
	if err := RegisterDevice(ctx, db, gateway); err != nil {
		log.Printf("网关注册失败: %v", err)
		return err
	}

	// 获取新插入的网关ID
	var gatewayID int
	if err := tx.GetContext(ctx, &gatewayID,
		"SELECT id FROM devices WHERE tenant_id = $1 AND device_id = $2",
		gateway.TenantID, gateway.DeviceID); err != nil {
		log.Printf("获取网关ID失败: %v", err)
		return err
	}

	// 批量注册子设备
	for _, dev := range subDevices {
		dev.ParentGatewayID = sql.NullInt64{Int64: int64(gatewayID), Valid: true}
		if err := RegisterDevice(ctx, db, dev); err != nil {
			log.Printf("子设备注册失败(%s): %v", dev.DeviceID, err)
			return err
		}
	}

	return db.Commit(tx)
}
